<template>
  <div v-loading="loading">
    <!-- 头部 -->
    <el-card class="head-content">
      <span class="head-content-txt">素材管理</span>
      <i class="el-icon-arrow-right head-content-txt" />
      <span class="head-content-txt">{{ titleObj[pageType] }}</span>
    </el-card>
    <!-- 主体 -->
    <el-card class="form-content">
      <el-form ref="form" :model="form" size="small" label-width="120px" :rules="rules">
        <el-form-item label="标题" prop="sourceTitle">
          <el-input v-model="form.sourceTitle" placeholder="请输入标题" class="baseItem" maxlength="30" show-word-limit type="text" />
        </el-form-item>
        <el-form-item label="分类" prop="classId">
          <el-select v-model="form.classId" placeholder="请选择分类" class="baseItem">
            <el-option
              v-for="label of labelDataList"
              :key="'label'+label.id"
              :label="label.className"
              :value="label.id"
            />
          </el-select>
        </el-form-item>
        <!-- 上传图片 -->
        <el-form-item label="内容" prop="imgList">
          <div class="tipText">图片最多可上传8张,每张大小1m内。</div>
          <el-upload
            v-show="imgList.length < 8"
            class="app-uploader-img-plus"
            :action="actionUrl"
            :show-file-list="false"
            multiple
            :file-list="imgList"
            :on-exceed="handleExceed"
            :headers="uploadHeaders"
            :limit="8"
            :on-success="(...arg) => handleAvatarSuccess('imgList',...arg)"
            :before-upload="(...arg) => beforeAvatarUpload('img',...arg)"
          >
            <i class="el-icon-plus app-uploader-img-plus-icon" />
          </el-upload>
          <div class="fileList">
            <div v-for="(file, idx) of imgList" :key="'fileList_'+idx" class="fileItem">
              <div class="clsoe">
                <i class="el-icon-delete" @click="removeFile(imgList,idx)" />
              </div>
              <el-image
                class="avatar"
                style="width: 100px; height: 100px"
                :src="file.path"
                fit="contain"
              />
            </div>
          </div>
        </el-form-item>
        <el-form-item label="源文件" prop="fileList">
          <div class="tipText">源文件最多可上传8个,每个大小10m内。支持.psd/.ai/.cdr</div>
          <el-upload
            v-show="fileList.length < 8"
            class="app-uploader-img-plus"
            :action="actionUrl"
            :show-file-list="false"
            :headers="uploadHeaders"
            :on-success="(...arg) => handleAvatarSuccess('file',...arg)"
            :before-upload="(...arg) => beforeAvatarUpload('file',...arg)"
          >
            <i class="el-icon-plus app-uploader-img-plus-icon" />
          </el-upload>
          <div class="fileList">
            <div v-for="(file, idx) of fileList" :key="file.path" class="fileItem">
              <div class="clsoe">
                <i class="el-icon-delete" @click="removeFile(fileList,idx)" />
              </div>
              <el-image
                class="avatar"
                style="width: 100px; height: 100px"
                :src="baseImg"
                fit="contain"
              />
              <div class="fileName">{{ file.fileName }}</div>
            </div>
          </div>
        </el-form-item>
        <!-- 可看范围 -->
        <SelectRole v-model="agtRadio" :form="form" />
        <el-form-item>
          <el-button @click="back">取消</el-button>
          <el-button type="primary" @click="save">保存</el-button>
        </el-form-item>
      </el-form>

    </el-card>
  </div>
</template>

<script>
import {
  sourceClassInfoList,
  sourceInfoAdd,
  sourceInfoUpd,
  sourceInfoDetail
} from '@/api/knowledge'
import { imgUploadUrl } from '@/api/upload'
import SelectRole from './components/SelectRole.vue'
import dayjs from 'dayjs'
import { getToken } from '@/utils/auth'
export default {
  components: {
    SelectRole
  },
  data() {
    return {
      agtRadio: 1,
      loading: false,
      titleObj: {
        add: '新增',
        edit: '编辑',
        detail: '查看'
      },
      baseImg: require('@/assets/file.png'),
      uploadHeaders: {
        'X-KDADMIN-TOKEN': getToken()
      },
      actionUrl: imgUploadUrl,
      form: {
        agtList: [],
        roleNm: [],
        sourceTitle: '',
        classId: '' // 分类
      },
      oldData: {},
      imgList: [],
      fileList: [],
      labelDataList: [],
      rules: {
        sourceTitle: [{ required: true, message: '请输入标题', trigger: ['blur', 'change'] }],
        classId: [{ required: true, message: '请输入分类', trigger: ['blur', 'change'] }],
        imgList: [{ validator: this.validRule, required: true, trigger: ['blur', 'change'] }],
        agtList: [{ validator: this.validRule, required: true, trigger: ['blur', 'change'] }],
        roleNm: [{ validator: this.validRule, required: true, trigger: ['blur', 'change'] }]
        // fileList: [{ validator: this.validRule, required: true, trigger: ['blur', 'change'] }]
      }
    }
  },
  computed: {
    pageType() {
      return this.$route.query.type || 'add'
    }
  },
  async mounted() {
    const { sourceId } = this.$route.query
    await this.getBasedata()
    if (['detail', 'edit'].includes(this.pageType)) {
      sourceInfoDetail({ id: sourceId }).then(res => {
        const detail = res.data
        const agtList = detail.agtList != '0' ? JSON.parse(detail.agtList) : []
        const obj = {
          ...res.data,
          agtList: agtList.map(item => item.agtId).filter(v => !!v),
          roleNm: detail.roleNm ? detail.roleNm.split(',') : []
        }
        this.imgList = JSON.parse(obj.sourcePath)
        this.fileList = JSON.parse(obj.resourcePath)
        this.form = obj
        this.oldData = res.data
        if (!this.labelDataList.find(label => label.id == this.form.classId)) {
          this.form.classId = ''
        }

        if (agtList.length) {
          this.agtRadio = 2
        } else {
          this.agtRadio = 1
        }
        console.log('详情 === ', this.form, this.imgList)
      })
    }
  },
  methods: {
    back() {
      this.$router.push({ name: 'MaterialManagement' })
    },
    save() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const classInfo = this.labelDataList.find(label => label.id == this.form.classId)
          console.log('classInfo', classInfo)

          // SelectRole组件中，根据agtList动态重组agtListObj数据
          const agtList = this.agtRadio == 1 ? [] : this.form.agtListObj
          // 过滤上传图片默认携带的多余字段
          const imgList = this.imgList.map(item => ({ path: item.path, fileName: item.fileName }))

          const resourceList = this.fileList.map(item => ({ path: item.path, fileName: item.fileName }))

          const obj = {
            sourceTitle: this.form.sourceTitle,
            classId: this.form.classId,
            classNm: classInfo.className,
            sourcePath: JSON.stringify(imgList),
            resourcePath: JSON.stringify(resourceList),
            agtList,
            roleNm: this.form.roleNm.join(','),
            status: 'Y'
          }
          console.log('obj', obj)
          if (classInfo.status == 'N') {
            this.$message.error('该分类已被禁用，请重新选择！')
            return
          }
          if (this.form.id) {
            sourceInfoUpd({
              ...obj,
              oldClassId: this.oldData.classId,
              id: this.form.id
            }).then(res => {
              console.log('res', res)
              this.$message.success('操作成功')
              this.back()
            })
          } else {
            sourceInfoAdd(obj).then(res => {
              console.log('res', res)
              this.$message.success('操作成功')
              this.back()
            })
          }
        }
      })
    },
    validRule(rule, value, callback) {
      const { field } = rule
      console.log('validRule', this.form)
      if (field == 'agtList') {
        if (this.agtRadio == 2 && !this.form.agtList.length) {
          callback('请选择机构')
        } else {
          callback()
        }
      } else if (field == 'roleNm') {
        if (this.agtRadio == 2 && (!this.form.roleNm || !this.form.roleNm.length)) {
          callback('至少选择一个范围')
        } else {
          callback()
        }
      } else if (field == 'imgList') {
        if (!this.imgList.length) {
          callback('请选择内容图片')
        } else {
          callback()
        }
      } else {
        callback()
      }
    },
    getBasedata() {
      return sourceClassInfoList({
        pageSize: 999,
        currentPage: 1
      }).then(res => {
        this.labelDataList = res.data.list
      })
    },
    removeFile(arr, index) {
      arr.splice(index, 1)
    },
    handleAvatarSuccess(type, res, file, fileList) {
      console.log('handleAvatarSuccess', type, res, file, fileList)
      // 新增状态判断，解决批量上传 同时通过:file-list绑定了数据源的情况下，on-success只执行一次问题
      if (fileList.every(item => item.status == 'success')) {
        this.loading = false
        if (res.code === 0) {
          const arr = fileList.map(item => {
            if (!item.response) return item

            const { baseUrl, path } = item.response.data
            return {
              path: baseUrl + path,
              fileName: item.name,
              status: item.status,
              uid: item.uid
            }
          })
          if (type == 'file') {
            this.fileList = arr
          } else {
            this.imgList = arr
            this.$refs['form'].validateField('imgList')
          }
        } else {
          this.$message.error(res.msg)
        }
      }
    },
    // 上传前处理
    async beforeAvatarUpload(type, file) {
      let result = false
      if (type == 'img') {
        result = await this.$beforeUploadFile(file, this, {
          fileType: 'img',
          fileSizes: 1
        })
      } else {
        result = await this.$beforeUploadFile(file, this, {
          fileSizes: 10,
          fileType: 'userValid',
          validNameTypeArr: ['psd', 'ai', 'cdr'],
          nameErrMsg: '仅支持.psd/.ai/.cdr格式'
        })
      }
      this.loading = result
      console.log('beforeUploadFile', result)
      return result ? Promise.resolve() : Promise.reject()
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handlePreview(file) {
      console.log(file)
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 8 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    }
  }
}
</script>

<style lang="scss" scoped="scoped">
.tipText{
  color: #b0acac;
  font-size: 12px;
}
.app-uploader-img-plus {
    width: 100px;
    height: 100px;
    border: 1px dotted #ddd;
    .avatar{
      width: 100px;
      height: 100px;
    }
    .app-uploader-img-plus-icon {
      font-size: 28px;
      color: #8c939d;
      width: 100px;
      height: 100px;
      line-height: 100px;
      text-align: center;
    }
  }

    .fileList{
      display: flex;
      .fileItem{
        display: inline-block;
        position: relative;
        margin-right: 10px;
        margin-bottom: 10px;
        max-width: 150px;
        text-align: center;
        line-height: 20px;
        .fileName{
          overflow:hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
        }
        .clsoe{
          position: absolute;
          z-index: 10;
          top: 0;
          right: 0;
          left: 0;
          bottom: 0;
          background: rgba($color: #000000, $alpha: 0.5);
          display: none;
          justify-content: center;
          align-items: center;
          i{
            color: #fff;
            font-size: 20px;
            cursor: pointer;
          }
        }
        &:hover{
          .clsoe{
            display: flex;
          }
        }
      }
    }

  .baseItem{
    width: 400px;
  }
  .head-content {
    width: 100%;

    .head-content-txt {
      font-size: 24px;
      font-weight: 550;
    }
  }
</style>
